import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import TableRow from './TableRow'
import DataModal from '../DataModal'
import DataTableStore from '../../stores/DataTableStore'
import DataTableActions from '../../actions/DataTableActions'
import Pagination from './Pagination'
import style from './DataTable.css'
import withStyles from '../../decorators/withStyles';

@withStyles(style)
class DataTable extends Component {

  constructor (props) {
    super(props)

    this.action = new DataTableActions()
    this.store = new DataTableStore(this.props.config, this.action) 
    this.state = {
      data: [],
      total: 0,
      page: 1,
      size: 10 // default page size
    }

    this.__data__ = {}  // current editing data item
  }

  static propTypes = {
    config: React.PropTypes.object.isRequired
  }

  componentDidMount () {
    this.store.addChangeListener(this._onDataRetrieved.bind(this))
    this.store.addCreateListener(this._onDataChanged.bind(this))
    this.store.addRemoveListener(this._onDataChanged.bind(this))
    this.store.addEditListener(this._onDataChanged.bind(this))

    this._readCurrentPageData()
  }

  componentWillUnmount () {
    this.store.removeListeners()
  }

  render() {
    let columns = $.extend(true, [], this.props.config.columns || [])
    let command = this.props.config.columns.slice(-1)[0]
    let data = this.state.data || []

    if (command.command) {
      columns.pop() 
    } else {
      command = null
    }

    let create = command && command.command[0].name === 'create'

    return (
      <div className="data-table">
        <table className="table table table-hover">
          <caption>
          {create && <a onClick={this._onTableRowClick.bind(this, 'create')} className="btn btn-sm btn-primary">
              <span className="glyphicon glyphicon-plus"></span>
              新增
            </a>
          }
          </caption>
          <thead>
            <tr>
              {columns.map(item => {
                return <th key={item.id || Math.random()}>{item.title}</th>
              })}

              {command && <th>{command.title || '操作'}</th>}
            </tr>
          </thead>
          <tbody>
            {data.map(item => {
                return <TableRow columns={columns} command={command} data={item} key={item.id || Math.random()} onClick={this._onTableRowClick.bind(this)} />
            })}
          </tbody>
        </table>
        <div className={cx({'load-overlay': true, show: !data.length})}></div>
        <Pagination total={this.state.total} size={this.state.size} page={this.state.page} onClick={this._onPaginationClick.bind(this)}/>
        <div id="__dataModalContainer"></div>
        <div id="__dataTableMessageArea" className="alert alert-success hide" role="alert">done</div>
      </div>
    )
  }

  _onTableRowClick (type, data) {
    this.__data__ = {} // reset

    if (data && data.id) {
      this.__data__ = data
    }

    let props = {
      onInit: this.props.onModalBodyInit,
      onChange: this._onChange.bind(this),
      onConfirm: this._onConfirm.bind(this, type),
      columns: this.props.config.columns,
      type: type,
      data: data
    }

    ReactDOM.render(<DataModal {...props} />, document.getElementById('__dataModalContainer')) 

    this.$$modal = document.getElementById('__dataModal')
    $(this.$$modal).modal()
  }

  _onChange (e) {
    let name = e.target.name
    let value = e.target.value
    this.__data__[name] = value
  }

  _onConfirm (type, e) {
    $(e.target).addClass('disabled')

    let data = this.__data__


    if (this.props.onSubmit) {
      this.props.onSubmit(data, result => {
        this._onDataChanged(result)
      })
    } else {
      switch(type) {
        case 'create':
          this.action.create(data)
          break
        case 'edit':
          this.action.update(data)
          break
        case 'delete':
          this.action.remove(data.id)
          break
      }
    }

  }

  _onDataRetrieved () {
    this.setState(this.store.getData())
  }

  _onDataChanged (ok) {
    $('#__dataModalSubmitButton').removeClass('disabled')

    if (ok) {
      if (this.$$modal) {
        $(this.$$modal).modal('hide')
      }
      this._showMessage('__dataTableMessageArea', '信息提交成功!')
      this._readCurrentPageData()
    } else {
      this._showMessage('__dataModalMessageArea', '信息提交失败!')
    }
  }

  _showMessage (id, msg) {
    let $alert = $(`#${id}`) 
    $alert.text(msg).hide().removeClass('hide').slideDown(() => {
      setTimeout(() => {
        $alert.slideUp()
      }, 2000)
    })
  }

  _readCurrentPageData () {
    this.store.read({
      size: this.state.size,
      page: this.state.page
    })
  }

  _onPaginationClick (page) {
    if (page && page !== this.state.page) {
      this.setState({
        page: page
      }, () => {
        this._readCurrentPageData()
      })
    }
  }

}

export default DataTable;
